package com.myownthemepark.s3vn;

/**
 * Continually request current repository revision from ZooKeeper and fetch revision to local storage
 * May run as a daemon.
 * 
 * @author alpha
 *
 */
public class UpdateRepo {
	public static void main(String[] args){
		String svnZooBucket = null;
		String svnZooPrefix = null;
		String svnZooZKAddr = null;
		String svnZooZKPrefix = null;
		String repoPath = null;
		S3vn s3vn = null;
		long currentRev, latestRev, rev;
		int ret;
		boolean failure = false;
		
		if (args.length != 1){
			System.out.println("Usage: java UpdateRepo <local repository path>");
			return;
		}
		
		try{
			repoPath = args[0];
			System.out.println("Repository name is " + repoPath);
			
			svnZooBucket = System.getenv("SVNZOO_BUCKET");
			svnZooPrefix = System.getenv("SVNZOO_PREFIX");
			svnZooZKAddr = System.getenv("SVNZOO_ZKADDR");
			svnZooZKPrefix = System.getenv("SVNZOO_ZKPREFIX");
			s3vn = new S3vn(repoPath, svnZooBucket, svnZooPrefix, svnZooZKAddr, svnZooZKPrefix);
			s3vn.setProgName("update");
			
			currentRev = s3vn.getCurrent();
			s3vn.createZKSession();
			while (true){ // This loop will not likely break
				latestRev = s3vn.watchCurrent(currentRev);
				System.out.println("Got notified that the latest rev is " + latestRev);
				for (rev = currentRev + 1; rev <= latestRev; rev++){
					System.out.println(String.format("UpdateRepo: for-loop: rev=%d currentRev=%d latestRev=%d", rev, currentRev, latestRev));
					s3vn.fetchRev(rev);
					s3vn.setCurrent(rev);
				}
				currentRev = latestRev;
			}
			// Execution will never reach here
		}catch (Exception e){
			System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
			StackTraceElement[] ste = e.getStackTrace();
			int i;
			for (i = 0; i < ste.length; i++){
				System.out.println(ste[i]);
			}
			failure = true;
			ret = 1; // This is the only place where ret might be assigned
		}finally{
			try{
				s3vn.releaseLock();
				s3vn.endZKSession();
			}catch (Exception e){
				System.err.println("[Error]: " + e.toString());
			}
		}
	}
}
